<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>实时电流电压监控</title>
    <script src="/js/echarts.min.js"></script>
    <!--    <script src="https://cdn.bootcss.com/echarts/5.3.2/echarts.min.js"></script>-->
</head>
<body>
<div id="lineChart" style="width: 900px;height:400px;"></div>
<script>
    // 初始化配置
    const MAX_RETRY_COUNT = 10;      // 最大重试次数
    const BASE_RECONNECT_DELAY = 1000; // 基础重连间隔(毫秒)
    let reconnectAttempts = 0;      // 当前重连尝试次数
    let isManualClose = false;      // 是否手动关闭标识

    const MAX_DATA_POINTS = 10; // 最大显示数据点数
    const CHART_THEME_COLOR = ['#5470C6', '#91CC75']; // 主题色（电流蓝，电压绿）
    let socket = null;

    // 初始化数据容器
    let chartData = {
        timestamps: [],
        current: [],
        voltage: []
    };

    // 初始化图表
    const chartDom = document.getElementById('lineChart');
    const myChart = echarts.init(chartDom);

    const baseOption = {
        title: {
            text: '实时电流电压监控',
            textStyle: {fontSize: 16}
        },
        tooltip: {
            // 触发方式
            trigger: 'axis',
            axisPointer: {type: 'cross'}
        },
        legend: {
            data: ['电流', '电压'],
            // right: 50
        },
        grid: {
            left: 50,
            right: 50,
            bottom: 20
        },
        xAxis: {
            // type: 'category',
            type: 'time', // 使用时间轴
            boundaryGap: false, // 数据紧贴边缘
            data: chartData.timestamps,
            axisLabel: {
                formatter: (value) => echarts.format.formatTime('hh:mm:ss', value)
            }
        },
        yAxis: [
            {
                name: '电流 (A)',
                type: 'value',
                position: 'left',
                axisLine: {lineStyle: {color: CHART_THEME_COLOR[0]}},
                splitLine: {show: false}
            },
            {
                name: '电压 (V)',
                type: 'value',
                position: 'right',
                offset: 0,
                axisLine: {lineStyle: {color: CHART_THEME_COLOR[1]}},
                splitLine: {show: false}
            }
        ],
        series: [
            {
                name: '电流',
                type: 'line',
                showSymbol: false,
                smooth: true,
                yAxisIndex: 0,
                itemStyle: {color: CHART_THEME_COLOR[0]},
                areaStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        {offset: 0, color: CHART_THEME_COLOR[0] + '80'},
                        {offset: 1, color: CHART_THEME_COLOR[0] + '10'}
                    ])
                },
                animation: false
            },
            {
                name: '电压',
                type: 'line',
                showSymbol: false,
                smooth: true,
                yAxisIndex: 1,
                itemStyle: {color: CHART_THEME_COLOR[1]},
                areaStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        {offset: 0, color: CHART_THEME_COLOR[1] + '80'},
                        {offset: 1, color: CHART_THEME_COLOR[1] + '10'}
                    ])
                },
                animation: false
            }
        ]
    };
    myChart.setOption(baseOption);

    // WebSocket连接管理
    function initWebSocket() {

        const handleClose = () => {
            if (!isManualClose && reconnectAttempts < MAX_RETRY_COUNT) {
                const delay = BASE_RECONNECT_DELAY * Math.pow(2, reconnectAttempts);
                console.log(`连接断开，将在 ${delay / 1000}s 后尝试第 ${reconnectAttempts + 1} 次重连`);

                setTimeout(() => {
                    reconnectAttempts++;
                    initWebSocket();
                }, delay);
            } else if (reconnectAttempts >= MAX_RETRY_COUNT) {
                console.error('已达到最大重连次数，停止重连');
            }
        };

        const handleError = (err) => {
            console.error('WebSocket错误:', err);
            socket.close(); // 触发close事件
        };

        // 清除旧连接
        if (socket) {
            socket.removeEventListener('close', handleClose);
            socket.removeEventListener('error', handleError);
            socket = null;
            // chartData = {
            //     timestamps: [],
            //     current: [],
            //     voltage: []
            // };
        }

        socket = new WebSocket('ws://' + window.location.host + '/ws/lineChart/1111');

        // 重置重连计数器（连接成功时）
        socket.addEventListener('open', () => {
            console.log('WebSocket connected');
            reconnectAttempts = 0;
        });

        socket.addEventListener('message', event => {
            try {
                const data = JSON.parse(event.data);

                // 数据验证
                if (!validateData(data)) {
                    console.warn('Invalid data format:', data);
                    return;
                }

                // 添加新数据
                chartData.timestamps.push(data.timestamp);
                chartData.current.push(parseFloat(data.current));
                chartData.voltage.push(parseFloat(data.voltage));

                // 保持数据长度
                if (chartData.timestamps.length > MAX_DATA_POINTS) {
                    chartData.timestamps.shift();
                    chartData.current.shift();
                    chartData.voltage.shift();
                }

                // 更新图表
                updateChart();
            } catch (error) {
                console.error('Data processing error:', error);
            }
        });

        socket.addEventListener('close', handleClose);
        socket.addEventListener('error', handleError);

    }

    // 数据格式验证
    function validateData(data) {
        return data &&
            typeof data.timestamp !== 'undefined' &&
            typeof data.current !== 'undefined' &&
            typeof data.voltage !== 'undefined' &&
            !isNaN(parseFloat(data.current)) &&
            !isNaN(parseFloat(data.voltage));
    }

    // 图表更新方法
    function updateChart() {
        const seriesOption = {
            // xAxis: {
            //     data: chartData.timestamps
            // },
            // series: [{
            //     data: chartData.current
            // }, {
            //     data: chartData.voltage
            // }],
            series: [
                {
                    data: chartData.current.map((v, i) => [chartData.timestamps[i], v])
                },
                {
                    data: chartData.voltage.map((v, i) => [chartData.timestamps[i], v])
                }
            ]
        };

        // 优化：仅当数据变化时更新
        myChart.setOption(seriesOption);
        // myChart.setOption(seriesOption, {notMerge: true});
    }


    // 新增手动关闭方法
    function closeWebSocket() {
        isManualClose = true;
        if (socket) {
            socket.close();
        }
    }

    // 页面隐藏时暂停重连
    // document.addEventListener('visibilitychange', () => {
    //     if (document.hidden) {
    //         closeWebSocket();
    //     } else {
    //         isManualClose = false;
    //         initWebSocket();
    //     }
    // });

    // 页面卸载前关闭连接
    window.addEventListener('beforeunload', () => {
        closeWebSocket();
    });

    // 初始化连接
    initWebSocket();

    // 窗口自适应
    window.addEventListener('resize', () => myChart.resize());

</script>
</body>
</html>
